<?
log_walk('-----------------',$_SERVER['REQUEST_URI']);

function getCacheArrayFileSystem($file){
	 $class_cache = array();
       if (file_exists($file))
        {
            $fp=fopen($file,'r');
            if ($fp)
            {
                while (!feof($fp))
                {
                    $str=fgets($fp);
                    $arr=explode(':',$str);
                    $class_cache[$arr[0]]=$arr[1];
                }
                fclose($fp);
            }
        }
     return $class_cache;
}

function getFromCache($class_name)
{
	$class_name=strtolower($class_name);
	global $class_cache;
	if (!count($class_cache))
	{
		$type=$GLOBALS['riaZoneType'];
		$file="../application/templates_c/cache/$type.dep";
		$class_cache = getCacheArrayFileSystem($file);
		$file="../application/templates_c/cache/doctrine.dep";
		$class_cache2 = getCacheArrayFileSystem($file);
        $class_cache = array_merge($class_cache,$class_cache2);
	}
	if (isset($class_cache[$class_name]))
	{
		include(trim($class_cache[$class_name]));
		log_walk($class_name,trim($class_cache[$class_name]));
		return true;
	}
	return false;
}

/**
 * Walks through the specified path, returns PHP files list
 *
 * @return array of PHP files
 */
function func_walk_dir($path,&$retval) {
	if (is_resource($dir = opendir($path))) {
        while (false !== ($file = readdir($dir))) {
            if ($file[0] == '.' || $file == 'CVS') continue;
            if (is_dir($path.'/'.$file)) {
                //$retval = array_merge($retval, func_walk_dir($path.'/'.$file));
                func_walk_dir($path.'/'.$file,$retval);
            } elseif (is_file($path.'/'.$file) && preg_match("/\.(php)$/", $file)) {
                $retval[str_replace('.php','',strtolower($file))] = $path.'/'.$file;
            }
        }
        closedir($dir);
    }
}


function getFromFileSystem($class_name)
{
	$class_name=strtolower($class_name);
	$type=$GLOBALS['riaZoneType'];

	if (is_dir('../application/classes/'.$type))
	{
		$dir_type=$type;
	}else{
		$dir_type='user';
	}
	
	$path=array("../../core2/classes",
				"../../core2/classes/extensions",
				"../application/managers/controls",
				"../application/classes/common",
				"../application/classes/$dir_type"
			);
			
		
	global $class_cache;
	foreach ($path as $item)
	{
		func_walk_dir($item,$class_cache);
	}
	if (isset($class_cache[$class_name]))
	{
		include($class_cache[$class_name]);
		log_walk($class_name,$class_cache[$class_name]);
		return true;
	}
	return false;
}

function log_walk($class_name,$path)
{
	func_log('NOTE '.$class_name.' : ['.$path.']', 'log_walk', LOG_INFO);
}

 function autoloadDBO($className)
 {
      if (class_exists($className, false) || interface_exists($className, false)) {
          return false;
      }

      $class = '../../core2/lib/' . str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';

      if (file_exists($class)) {
      	  $fp=fopen("../application/templates_c/cache/doctrine.dep",'a');
          fwrite($fp,strtolower($className).":$class\n");
          fclose($fp);
          require $class;

          return true;
      }
      Doctrine::loadModels(array('../application/managers/orm','../../core2/classes/managers/orm'));
      $loadedModels = Doctrine::getLoadedModelFiles();
      if (isset($loadedModels[$className]) && file_exists($loadedModels[$className])) {
      	  $fp=fopen("../application/templates_c/cache/doctrine.dep",'a');
          fwrite($fp,strtolower($className).":".$loadedModels[$className]."\n");
          fclose($fp);
          require $loadedModels[$className];

          return true;
      }

      return false;
 }

function __autoload($class_name)
{
	$type=$GLOBALS['riaZoneType'];
	if (!class_exists($class_name, false)) {
		if (!getFromCache($class_name))
		{
			if (getFromFileSystem($class_name))
			{
				if (!is_dir('../application/templates_c/cache'))
				{
					mkdir('../application/templates_c/cache');
					chmod('../application/templates_c/cache',0777);
				}
				global $class_cache;
				$fp=fopen("../application/templates_c/cache/$type.dep",'w');
				foreach ($class_cache as $key=>$item)
				{
					fwrite($fp,"$key:$item\n");
				}
				fclose($fp);
			}elseif (!autoloadDBO($class_name)){
				if (strstr($class_name,'Dialog')!==false){
					func_log("Class load Error: $class_name",'load_modules');
					$str = 'class '.$class_name.' extends Controller 
						{
							function prepare()
							{
								$this->redirect(\'/\');
							}
						}';
					eval($str);
				}
			}
		}
	}


}

/**
 * Profiler function
 *
 */
	function func_profiler(){
    	global $profiler,$options;
   		$print = true;
   		ob_start();
    	if ($GLOBALS['options']['logger']['profiler_file']!=''){
    		$print=false;
    		$logDir  = $options['logger']['log_files_dir'];
    		if (substr($logDir, -1, 1) != '/') {
        		$logDir .= '/';
    		}
    		$fp = fopen($logDir.$GLOBALS['options']['logger']['profiler_file'],'a');
    		echo "\n===============================================\n".date("Y-m-d H:i:s")."\n";
    	} 	
        $time = 0;
		foreach ($profiler as $event) {
			if ($print){
				echo '<div style="border:1px solid #000000;margin:5px;padding:5px;"><b>';
			}else{
				echo "\n----------\n";
			}
		    $time += $event->getElapsedSecs();
		    echo $event->getName() . " " . sprintf("%f", $event->getElapsedSecs()) . "";
		    if ($print){
		    	echo '</b><pre class="prettyprint lang-sql">';
		    }else{
		    	echo "\n\n";
		    }
		    echo wordwrap($event->getQuery());
		    if ($print){
		    	echo "</pre>";
		    }else{
		    	echo "\n";
		    }
		    $params = $event->getParams();
		    if( ! empty($params)) {
		        var_dump($params);
		    }
		    if ($print){
		    	echo '</div>';
		    }else{
		    	echo "\n";
		    }
		}
		if ($print){
			echo "<font color='red'>Total time: " . $time  . "</font><br>\n";
		}else{
			echo "Total time: " . $time  . "\n";
		}
		$text = ob_get_contents();
		ob_clean();
		if ($print){
			print $text;
		}else{
			fwrite($fp,$text);
			fclose($fp);
		}
    }

/**
 * Logger function
 *
 * @todo  limit messages with default level
 * @param string log message
 * @param string component name
 * @param integer LOG_LEVEL
 */
function func_log($message, $component = 'log', $level = LOG_INFO) {
    // construct log file name, depending on component name
    global $options, $priorities;
    if (!$options['logger']['enabled'] || $level > $options['logger']['level']) {
        return;
    }
    $logDir  = $options['logger']['log_files_dir'];
    if (substr($logDir, -1, 1) != '/') {
        $logDir .= '/';
    }
    $component = str_replace(' ', '_', strtolower($component));
    $logFile = $component . '.log.' . date("m-d-Y");
    $logPath = $logDir . $logFile;
    $mypid = getmypid();
    $mypid = $mypid == false ? 0 : $mypid;
    $logMsg  = sprintf("%s (%d) %s - %s - %s\n", date("Y-m-d H:i:s"), $mypid, $component, $priorities[$level], $message);
    $fp = fopen($logPath, "a");
    if ($fp) {
        fwrite($fp, $logMsg);
        fclose($fp);
    }
}


// error handler function
function myErrorHandler($errno, $errstr, $errfile, $errline)
{
  switch ($errno) {
  case E_USER_ERROR:
    echo "<font size='1'><table dir='ltr' border='1' cellspacing='0' cellpadding='1'>";
    echo "<tr><th align='left' bgcolor='#f57900'><span style='background-color: #cc0000; color: #fce94f; font-size: x-large;'>( ! )</span> <b>ERROR IN RIA FRAMEWORK</b> [$errno]</th></tr>";
    echo "<tr><th align='left' bgcolor='#e9b96e'>Fatal error in line $errline of file $errfile</th></tr>";
    echo "<tr><td align='left' bgcolor='#eeeeec'><pre>$errstr</pre></td></tr>";
    echo "</table></font>\n";
    exit(1);
    break;
  case E_USER_WARNING:
    echo "<b>WARNING IN RIA FRAMEWORK</b> [$errno] <pre>$errstr</pre><br />\n";
    break;
  case E_USER_NOTICE:
    echo "<b>NOTICE IN RIA FRAMEWORK</b> [$errno] <pre>$errstr</pre><br />\n";
    break;
  }
}

?>